﻿using System;
using System.Collections.Generic;
using WEB.Core.Controls;
using Ext.Net;
using WEB.Core.Util;
using log4net;
using WEB.BLL.Services;
using WEB.BLL.Entities;
using WEB.BLL;
using System.Web.Security;

namespace WEB.APP.Modules.List
{
    public partial class BreifCVDetail : BasePage
    {
        public BreifCVDetail()
            : base(SCREENS.BREIFCVDETAIL, false)
        {
        }

        protected enum Mode
        {
            View,
            Add,
            Edit
        }

        protected override void Page_Load(object sender, EventArgs e)
        {
            AddListControlAdd(tbsAdd, btnNew);
            base.Page_Load(sender, e);
        }

        protected override void NotPostBack()
        {
            base.NotPostBack();
            ResourceManager.RegisterOnReadyScript("ChangeMode('View');");
            
            if (CurrentUser.RoleId == -1)
            {
                cbStudentID.Value = Util.Obj2Decimal(CurrentUser.UserName);
                ResourceManager.RegisterOnReadyScript("MethodNamespace.LoadData();");
            }
            else if (!string.IsNullOrEmpty(Request["id"]))
            {
                ResourceManager.RegisterOnReadyScript(string.Format("cbStudentID.setValue({0}); MethodNamespace.LoadData();", Request["id"]));
            }
        }

        [DirectMethod]
        public void LoadExpertiseCv()
        {
            try
            {
                IList<ExpertiseCVEntity> _lst = ExpertiseCVService.GetInstance().LoadByStudentId(new ExpertiseCVEntity(){ StudentId = Convert.ToDecimal(cbStudentID.Value) });
                if (_lst == null)
                    return;
                storeExpertiseCv.DataSource = _lst;
                storeExpertiseCv.DataBind();
                
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }

        [DirectMethod]
        public void LoadData()
        {
            try
            {
                var CvE = new CvEntity() { StudentId = Convert.ToDecimal(cbStudentID.Value) };
                CvE = CvService.GetInstance().LoadPrimaryKeyEX(CvE);
                if (CvE == null)
                {
                    if (CurrentUser.RoleId == -1)
                    {
                        winDetails.Reset();
                        var _Script = "ChangeMode('Add');cbStudentID.setDisabled(true);";
                        StudentEntity _ett = StudentService.GetInstance().LoadByPrimaryKey(new StudentEntity() { StudentId = Convert.ToDecimal(CurrentUser.UserName) });
                        if (_ett == null)
                        {
                            FormsAuthentication.SignOut();
                            FormsAuthentication.RedirectToLoginPage();
                        }
                        _Script += String.Format("cbStudentID.setValue('{0}');tfStudentName.setValue('{1} {2}');", _ett.StudentId, _ett.GivenName, _ett.SurName);
                        ResourceManager.RegisterOnReadyScript(_Script);
                        LoadExpertiseCv();
                        cbStudentID.Disabled = true;
                    }
                    return;
                }

                tfStudentName.Text = CvE.StudentName;

                if (CvE.Interested)
                    InterestedR1.Checked = true;
                else
                    InterestedR2.Checked = true;
                taComment.Text = CvE.Comment;
                if (!string.IsNullOrEmpty(CvE.OtherSkill))
                {
                    string _temp = "";
                    int _i = 1;
                    foreach (var item in CvE.OtherSkill.Split(','))
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            _temp += String.Format("{0}. {1}\n", _i, item.Trim());
                            _i++;
                        }
                    }
                    taOtherSkill.Text = _temp;
                }
                //cbProjectType.Value = CvE.ProjectType;
                foreach (var item in CvE.ProjectType.Split(','))
                {
                    if (string.IsNullOrEmpty(item))
                        continue;
                    switch (item)
                    {
                        case "1":
                            cgProjectTypeR1.Checked = true;
                            break;
                        case "2":
                            cgProjectTypeR2.Checked = true;
                            break;
                        case "3":
                            cgProjectTypeR3.Checked = true;
                            break;
                        case "4":
                            cgProjectTypeR4.Checked = true;
                            break;
                        case "5":
                            cgProjectTypeR5.Checked = true;
                            break;
                        case "6":
                            cgProjectTypeR6.Checked = true;
                            break;
                        case "7":
                            cgProjectTypeR7.Checked = true;
                            break;
                        case "8":
                            cgProjectTypeR8.Checked = true;
                            break;
                        case "9":
                            cgProjectTypeR9.Checked = true;
                            break;
                        default:
                            break;
                    }
                }

                LoadExpertiseCv();
                switch ((int)CvE.ElectiveLeft)
                {
                    case 0:
                        rgElectiveLeftR3.Checked = true;
                        break;
                    case 1:
                        rgElectiveLeftR2.Checked = true;
                        break;
                    case 2:
                        rgElectiveLeftR1.Checked = true;
                        break;
                }
                if (CurrentUser.RoleId == -1)
                    ResourceManager.RegisterOnReadyScript("ChangeMode('Edit');");
            }
            catch (Exception ex)
            {
                Notification(ex);
            }

        }

        [DirectMethod]
        public void SaveData(string jsonData, bool Edit)
        {
            try
            {
                List<ExpertiseCVEntity> lstJson = new List<ExpertiseCVEntity>();
                lstJson = JSON.Deserialize<List<ExpertiseCVEntity>>(jsonData);

                var CvE = new CvEntity()
                {
                    StudentId = Convert.ToDecimal(cbStudentID.Value),
                    //ProjectType = Convert.ToDecimal(cbProjectType.Value),
                    Interested = InterestedR1.Checked
                };

                if (rgElectiveLeftR1.Checked)
                    CvE.ElectiveLeft = 2;
                else if (rgElectiveLeftR2.Checked)
                    CvE.ElectiveLeft = 1;
                else if (rgElectiveLeftR3.Checked)
                    CvE.ElectiveLeft = 0;

                string _temp = "";
                foreach (var item in cgProjectType.Items)
                    if(item.Checked)
                        _temp += item.ID.Substring(item.ID.Length - 1) + ",";
                if (!string.IsNullOrEmpty(_temp))
                    CvE.ProjectType = _temp.Remove(_temp.Length - 1);

                if (!string.IsNullOrEmpty(taComment.Text.Trim()))
                    CvE.Comment = taComment.Text.Trim();
                if (!string.IsNullOrEmpty(taOtherSkill.Text.Trim()))
                {
                    _temp = "";
                    foreach (var item in taOtherSkill.Text.Split('\n'))
                    {
                        if (!string.IsNullOrEmpty(item))
                        {
                            _temp += item.Substring(item.IndexOf('.') + 1) + ", ";
                        }
                    }
                    CvE.OtherSkill = _temp.Remove(_temp.Length - 2);
                }

                if (CurrentUser.RoleId == -1)
                {
                    if (CvService.GetInstance().LoadPrimaryKeyEX(new CvEntity() { StudentId = Convert.ToDecimal(cbStudentID.Value) }) == null)
                    {
                        CvService.GetInstance().Insert(CvE);
                        foreach (var item in lstJson)
                        {
                            if (!item.Checked)
                                continue;
                            item.StudentId = CvE.StudentId;
                            ExpertiseCVService.GetInstance().Insert(item);
                        }
                    }
                    else
                    {
                        CvService.GetInstance().Update(CvE);
                        foreach (var item in lstJson)
                        {
                            item.StudentId = CvE.StudentId;
                            ExpertiseCVService.GetInstance().InsertEX(item);
                        }
                    }
                }
                if (Edit)
                {
                    CvService.GetInstance().Update(CvE);
                    foreach (var item in lstJson)
                    {
                        item.StudentId = CvE.StudentId;
                        ExpertiseCVService.GetInstance().InsertEX(item);
                    }
                }
                else
                {
                    CvService.GetInstance().Insert(CvE);
                    foreach (var item in lstJson)
                    {
                        if (!item.Checked)
                            continue;
                        item.StudentId = CvE.StudentId;
                        ExpertiseCVService.GetInstance().Insert(item);
                    }
                }
                Msg.Informational("Save data successful.");
                if(CurrentUser.RoleId != -1)
                    ResourceManager.RegisterOnReadyScript("ChangeMode('View');");
                else
                    ResourceManager.RegisterOnReadyScript("ChangeMode('Edit');");
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }
        
        [DirectMethod]
        public void Delete()
        {
            try
            {
                ExpertiseCVEntity ExpertiseCVE = new ExpertiseCVEntity() { StudentId = Convert.ToDecimal(cbStudentID.Value) };
                ExpertiseCVService.GetInstance().DeleteByStudentId(ExpertiseCVE);

                CvEntity CvE = new CvEntity { StudentId = ExpertiseCVE.StudentId };
                CvService.GetInstance().Delete(CvE);
            }
            catch (Exception ex)
            {
                Notification(ex);
            }
        }

        [DirectMethod]
        public void CheckRole()
        {
            if (CurrentUser.RoleId == -1)
            {
                FormsAuthentication.SignOut();
                FormsAuthentication.RedirectToLoginPage();
                Response.Redirect("~/");
            }
        }
    }
}
